package com.party.web.web.controller.member;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.party.api.dto.wechat.requst.XcxQrCodeRequest;
import com.party.common.constant.Constant;
import com.party.common.paging.Page;
import com.party.common.utils.DateUtils;
import com.party.common.utils.LangUtils;
import com.party.common.utils.StringUtils;
import com.party.core.dao.read.member.PartnerMemberReadDao;
import com.party.core.model.BaseModel;
import com.party.core.model.activity.Activity;
import com.party.core.model.commune.*;
import com.party.core.model.member.Member;
import com.party.core.model.member.MemberGroup;
import com.party.core.model.member.PartnerMember;
import com.party.core.model.notify.TargetTemplate;
import com.party.core.model.photo.PhotoProject;
import com.party.core.model.wechatPlatform.WechatOpenMember;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.commune.ICIntegralBizService;
import com.party.core.service.commune.ICIntegralItemService;
import com.party.core.service.commune.ICIntegralTypeService;
import com.party.core.service.commune.ICUserIntegralService;
import com.party.core.service.commune.impl.CMemberIntegralBizService;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.service.member.IMemberService;
import com.party.core.service.member.IPartnerMemberService;
import com.party.core.service.wechatPlatform.IWechatOpenMemberService;
import com.party.web.biz.file.FileBizService;
import com.party.web.biz.member.CIntegralBizToService;
import com.party.web.biz.member.CMomentBizService;
import com.party.web.biz.member.MemberIntegralNotifyService;
import com.party.web.biz.system.member.MemberGroupBizService;
import com.party.web.utils.RealmUtils;
import com.party.web.utils.excel.ExportExcel;
import com.party.web.web.dto.AjaxResult;
import com.party.web.web.dto.input.common.CommonInput;
import com.party.web.web.dto.output.member.CMomentSave;
import com.party.web.web.security.CurrentUser;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @program: party
 * @description: 用户积分控制器
 * @author: Hua Qunhao
 * @create: 2019-08-14 10:34
 **/
@Controller
@RequestMapping("member/integral/userIntegral")
public class IntegralUserController {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private ICUserIntegralService userIntegralService;
    @Autowired
    private ICIntegralTypeService integralTypeService;
    @Autowired
    private IPartnerMemberService partnerMemberService;
    @Autowired
    private ICIntegralItemService integralItemService;
    @Autowired
    private IMemberService memberService;
    @Autowired
    private IWechatOpenMemberService wechatOpenMemberService;
    @Autowired
    private FileBizService fileBizService;
    @Autowired
    private ICIntegralBizService integralBizService;
    @Autowired
    private IActivityService activityService;
    @Autowired
    private MemberIntegralNotifyService memberIntegralNotifyService;
    @Autowired
    private IMemberGroupService memberGroupService;

    @Autowired
    private CIntegralBizToService cIntegralBizToService;
    @Autowired
    private PartnerMemberReadDao partnerMemberReadDao;
    @Autowired
    private CMomentBizService momentBizService;
    @Autowired
    private CMemberIntegralBizService memberIntegralBizService;
    private ExecutorService threadPool = Executors.newFixedThreadPool(5);

    /**
     * @Description: 用户积分列表
     * @Param: [CIntegralType, input, page]
     * @return: org.springframework.web.servlet.ModelAndView
     * @Author: Hua Qunhao
     * @Date: 2019/8/14
     */
    @RequestMapping("/list")
    public ModelAndView list(CUserIntegral cUserIntegral, CommonInput input, Page page) {
        page.setLimit(20);
        ModelAndView mv = new ModelAndView("member/cUserIntegralList");
        CurrentUser currentUser = RealmUtils.getNewCurrentUser();
        if (StringUtils.isEmpty(cUserIntegral.getPmId())) {
            return null;
        }
        //带时间查询
        input.setIsDate(1);
        Map<String, Object> params = CommonInput.appendParams(input);

        PartnerMember partnerMember = partnerMemberService.get(cUserIntegral.getPmId());

        String newPartnerId = null;
        boolean isChild = currentUser.isChild();
        if (isChild) {
            newPartnerId = currentUser.getPartnerId();
        } else {
            newPartnerId = currentUser.getId();
        }

        params.put("cuiPartnerId", newPartnerId);
        params.put("cuiMemberId", partnerMember.getMemberId());

        if (StringUtils.isNotEmpty(cUserIntegral.getIntegralItemName())) {
            params.put("cItemName", cUserIntegral.getIntegralItemName());
        }
        if (StringUtils.isNotEmpty(cUserIntegral.getIntegralTypeId())) {
            params.put("cTypeId", cUserIntegral.getIntegralTypeId());
            params.put("typeId", cUserIntegral.getIntegralTypeId());
        }
        if (StringUtils.isNotEmpty(input.getcIntegralTypeId())) {
            cUserIntegral.setIntegralTypeId(input.getcIntegralTypeId());
            params.put("cTypeId", input.getcIntegralTypeId());
            params.put("typeId", input.getcIntegralTypeId());
        }

        List<CUserIntegralOutput> cUserIntegralOutputs = userIntegralService.queryUserIntegralList(params, page);

        //若当前登录的是子账号，返回的是主账号的id，否则返回当前登录机构的id
        CIntegralType cIntegralType = new CIntegralType();
        cIntegralType.setCreateBy(newPartnerId);
        List<CIntegralType> cIntegralTypes = integralTypeService.list(cIntegralType);

        //该用户获得积分总数
        Double fractionSum = userIntegralService.getUserItemFractionSumWithParams(params);

        Member member = memberService.get(partnerMember.getMemberId());

        mv.addObject("cIntegralTypes", cIntegralTypes);
        mv.addObject("cUserIntegralOutputs", cUserIntegralOutputs);
        mv.addObject("cUserIntegral", cUserIntegral);
        mv.addObject("fractionSum", fractionSum);
        mv.addObject("member", member);
        mv.addObject("input", input);
        mv.addObject("page", page);
        mv.addObject("isChild", isChild);
        mv.addObject("isXzgsAdmin", currentUser.isXzgsAdmin());
        return mv;
    }

    /**
     * @Description:编辑积分
     * @Param:CIntegralItem
     * @return:AjaxResult
     * @Author: Hua Qunhao
     * @Date: 2019/8/13
     */
    @ResponseBody
    @RequestMapping(value = "/saveOrUpdate", method = RequestMethod.POST)
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult saveOrUpdate(CUserIntegral cUserIntegral) {
        try {
            if (StringUtils.isEmpty(cUserIntegral.getMemberId()) && StringUtils.isEmpty(cUserIntegral.getId())) {
                return AjaxResult.error("参数为空");
            }
            if (StringUtils.isEmpty(cUserIntegral.getIntegralItemId())) {
                return AjaxResult.error("参数为空");
            }
            CIntegralItem cIntegralItem = integralItemService.get(cUserIntegral.getIntegralItemId());
            if (null == cIntegralItem) {
                return AjaxResult.error("积分项不存在");
            }
            if (StringUtils.isEmpty(cUserIntegral.getId())) {
                String partnerId = memberGroupBizService.getXzgsMemberId();
                cUserIntegral.setPartnerId(partnerId);
                userIntegralService.insert(cUserIntegral);
            } else {
                CUserIntegral db = userIntegralService.get(cUserIntegral.getId());
                db.setIntegralTypeId(cUserIntegral.getIntegralTypeId());
                db.setIntegralItemId(cUserIntegral.getIntegralItemId());
                userIntegralService.update(db);
            }


            //更新用户积分表
            ArrayList<String> memberIds = Lists.newArrayList();
            memberIds.add(cUserIntegral.getMemberId());
            //更新用户积分表
            final List<String> final_members = memberIds;
            threadPool.execute(() -> {
                try {
                    memberIntegralBizService.refreshCMemberIntegral(final_members);
                }catch (Exception e){
                    logger.error("编辑积分--更新用户积分表---失败");
                }
            });
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("编辑积分异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("编辑积分异常");
        }
    }

    /**
     * @Description:获取积分详情
     * @Param:CIntegralItem
     * @return:AjaxResult
     * @Author: Hua Qunhao
     * @Date: 2019/8/13
     */
    @RequestMapping(value = "/form")
    public ModelAndView form(String id, String memberId) {
        ModelAndView mv = new ModelAndView("member/cUserIntegralForm");
        CurrentUser currentUser = RealmUtils.getNewCurrentUser();

        CIntegralType cIntegralType = new CIntegralType();
        if (currentUser.isChild()) {
            cIntegralType.setCreateBy(currentUser.getPartnerId());
        } else {
            cIntegralType.setCreateBy(currentUser.getId());
        }
        ArrayList<Integer> categorys = Lists.newArrayList();
        categorys.add(IntegralType.CINTEGRALTYPE_CATEGORY_GIFT.getCode());
        categorys.add(IntegralType.CINTEGRALTYPE_CATEGORY_ORDINARY.getCode());
        cIntegralType.setCategorys(categorys);
        List<CIntegralType> cIntegralTypes = integralTypeService.list(cIntegralType);
        mv.addObject("cIntegralTypes", cIntegralTypes);
        mv.addObject("memberId", memberId);

        if (StringUtils.isNotEmpty(id)) {
            CUserIntegral cUserIntegral = userIntegralService.get(id);
            mv.addObject("cUserIntegral", cUserIntegral);
        }
        return mv;
    }

    /**
     * @Description:删除积分
     * @Param:CIntegralItem
     * @return:AjaxResult
     * @Author: Hua Qunhao
     * @Date: 2019/8/13
     */
    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult delete(String id) {
        try {
            if (StringUtils.isEmpty(id)) {
                return AjaxResult.error("参数为空");
            }
            CUserIntegral cUserIntegral = userIntegralService.get(id);
            cUserIntegral.setDelFlag(BaseModel.DEL_FLAG_DELETE);
            userIntegralService.update(cUserIntegral);

            //更新用户积分表
            ArrayList<String> memberIds = Lists.newArrayList();
            memberIds.add(cUserIntegral.getMemberId());
            final List<String> final_members = memberIds;
            threadPool.execute(() -> {
                try {
                    memberIntegralBizService.refreshCMemberIntegral(final_members);
                }catch (Exception e){
                    logger.error("删除积分-更新用户积分表---失败");
                }
            });
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("删除积分异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("删除积分异常");
        }
    }


    /**
     * @Description: 生成小程序二维码
     * @Param: [pmId]
     * @return: com.party.web.web.dto.AjaxResult
     * @Author: Hua Qunhao
     * @Date: 2019/8/15
     */
    @ResponseBody
    @RequestMapping("/checkXcxQrCode")
    public AjaxResult checkXcxQrCode(String pmId, Integer type) {
        if (StringUtils.isEmpty(pmId) || (type == null || type == 0)) {
            return AjaxResult.error("参数不能为空");
        }
        try {
            PartnerMember partnerMember = partnerMemberService.get(pmId);
            if (null == partnerMember) {
                return AjaxResult.error("partnerMember对象为空");
            }
            HashMap<Integer, String> mmp = Maps.newHashMap();
            //个人资料邀请二维码
            mmp.put(1, "pages/card/index");
            //海报邀请二维码
            mmp.put(2, "pages/slogin/index");

            String tagUrl = mmp.get(type);
            if (StringUtils.isEmpty(tagUrl)) {
                return AjaxResult.error("获取小程序二维码图片异常 pmId:" + pmId + ", type:" + type);
            }

            WechatOpenMember openMember = wechatOpenMemberService.findByType(Constant.WECHAT_ACCOUNT_TYPE_SYSTEM_XCX_INTEGRAL);
            XcxQrCodeRequest qrCodeRequest = new XcxQrCodeRequest();
            qrCodeRequest.setPage(tagUrl);
            qrCodeRequest.setScene(pmId);
            String filePath = fileBizService.getUploadCIPath(partnerMember.getPartnerId(), "integral");
            String result = fileBizService.uploadCloudOut(pmId, filePath, qrCodeRequest, openMember.getAuthorizerAccessToken(), 1);
            if (StringUtils.isEmpty(result)) {
                throw new Exception("生成小程序码异常");
            }
            return AjaxResult.success(result);
        } catch (Exception e) {
            logger.error("生成小程序码异常", e);
            return AjaxResult.error("异常");
        }
    }

    /**
     * @Description:批量添加积分
     * @Param:CIntegralItem
     * @return:AjaxResult
     * @Author: Hua Qunhao
     * @Date: 2019/8/13
     */
    @ResponseBody
    @RequestMapping(value = "/batchAddIntegral", method = RequestMethod.POST)
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult batchAddIntegral(CUserIntegral cUserIntegral, Integer isSendMessages,
                                       String behavior, TargetTemplate targetTemplate, String sendTimeString, Integer type) {

        if (StringUtils.isEmpty(cUserIntegral.getIntegralItemId()) ||
                StringUtils.isEmpty(cUserIntegral.getActivityId()) ||
                null == type
        ) {
            return AjaxResult.error("参数为空");
        }
        if (isSendMessages == 1 && StringUtils.isEmpty(sendTimeString)) {
            return AjaxResult.error("dateTime不能为空");
        }

        try {
            CIntegralItem cIntegralItem = integralItemService.get(cUserIntegral.getIntegralItemId());
            if (null == cIntegralItem) {
                return AjaxResult.error("积分项不存在");
            }
            Activity activity = activityService.get(cUserIntegral.getActivityId());
            if (null == activity) {
                return AjaxResult.error("活动不存在");
            }
            Integer memberType = 1;
            if (type == 10) {
                memberType = 0;
            }
            cUserIntegral.setMemberType(memberType);

            //添加积分
            List<String> members = integralBizService.batchAddIntegralAct(cUserIntegral, activity.getMember());

            //发布动态
            final CMomentSave cMomentSave = new CMomentSave();
            cMomentSave.setPartnerId(activity.getMember());
            cMomentSave.setBizId(activity.getId());
            cMomentSave.setMomentType(MomentType.ADD_INTEGRAL.getCode());
            Map<String, Object> mmp = Maps.newHashMap();
            mmp.put("activityId", activity.getId());
            mmp.put("createBy", activity.getMember());
            String[] strings = members.toArray(new String[members.size()]);
            mmp.put("memberIds", String.join(",", strings));
            mmp.put("itemFraction", cIntegralItem.getItemFraction());
            cMomentSave.setDatas(mmp);

            threadPool.execute(() -> {
                try {
                    momentBizService.businessSaveCMoment(cMomentSave);
                } catch (Exception e) {
                    logger.error("批量添加积分同时发布动态---失败");
                }
            });
            //添加积分通知
            if (isSendMessages == 1) {
                Date date = null;
                if (sendTimeString.indexOf(":") == sendTimeString.lastIndexOf(":")) {
                    sendTimeString = sendTimeString + ":00";
                }
                try {
                    date = DateUtils.parse(sendTimeString, "yyyy-MM-dd HH:mm:ss");
                } catch (ParseException e) {
                    logger.error("定时推送短信失败, 时间参数有误 dateTime = {}", sendTimeString, e);
                    return AjaxResult.error("定时推送短信失败, 时间参数有误 dateTime = " + sendTimeString);
                }
                targetTemplate.setTargetId(activity.getId());

                final Date final_date = date;
                final CUserIntegral final_cUserIntegral = cUserIntegral;
                final String final_member = activity.getMember();
                final TargetTemplate fnal_targetTemplate = targetTemplate;
                threadPool.execute(() -> {
                    try {
                        memberIntegralNotifyService.sendAddIntegraSms(final_cUserIntegral, final_member, "add", fnal_targetTemplate, final_date, Constant.SEND_SHORT_MESSAGE_TYPE_INTEGRAL);
                    } catch (Exception e) {
                        logger.error("定时推送短信失败, ", e);
                    }
                });
            }
            //更新用户积分表
            final List<String> final_members = members;
            threadPool.execute(() -> {
                try {
                    memberIntegralBizService.refreshCMemberIntegral(final_members);
                }catch (Exception e){
                    logger.error("批量添加积分同时更新用户积分表---失败");
                }
            });
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("批量添加积分异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("批量添加积分异常" + e.getMessage());
        }
    }


    /**
     * @Description:用户积分类型冗余字段维护
     * @Param:CIntegralItem
     * @return:AjaxResult
     * @Author: Hua Qunhao
     * @Date: 2019/8/13
     */
    @ResponseBody
    @RequestMapping(value = "/userIntegralTypeIdMaintain", method = RequestMethod.GET)
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult userIntegralTypeIdMaintain() {
        try {
            List<CUserIntegral> list = userIntegralService.list(new CUserIntegral());
            for (CUserIntegral cui : list) {
                CIntegralItem cIntegralItem = integralItemService.get(cui.getIntegralItemId());
                CIntegralType cIntegralType = integralTypeService.get(cIntegralItem.getTypeId());
                cui.setIntegralTypeId(cIntegralType.getId());
                userIntegralService.update(cui);
            }
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("用户积分类型冗余字段维护异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("用户积分类型冗余字段维护异常");
        }
    }


    /**
     * @Description:获取推荐的人列表
     * @Param: [cUserIntegral, input, page]
     * @return: org.springframework.web.servlet.ModelAndView
     * @Author: Hua Qunhao
     * @Date: 2019/9/9
     */
    @RequestMapping("recommendPersonList")
    public ModelAndView recommendPersonlist(String mobile, CommonInput input, Page page) {
        page.setLimit(20);
        ModelAndView mv = new ModelAndView("member/recommendPersonlist");
        CurrentUser currentUser = RealmUtils.getNewCurrentUser();
        if (StringUtils.isEmpty(input.getPmId())) {
            return null;
        }
        //带时间查询
        input.setIsDate(1);
        //推荐人 用户机构关系id---pmId
        Map<String, Object> params = CommonInput.appendParams(input);
        if (StringUtils.isNotEmpty(input.getPmId())) {
            params.put("pmId", input.getPmId());
        }

//        params.put("partnerId", partnerId);
        if (StringUtils.isNotEmpty(mobile)) {
            params.put("mobile", mobile);
        }

        if (null != input.getcIntegralTypeId()) {
            params.put("typeId", input.getcIntegralTypeId());
        }


        //子账号查主账号下的积分类型
        String partnerId = currentUser.getId();
        if (currentUser.isChild()) {
            partnerId = currentUser.getPartnerId();
        }
        params.put("cuiPartnerId", partnerId);

        List<String> orgIds = memberGroupService.getChildWithMy(partnerId);
        params.put("orgIds", orgIds);

        List<CIntegralType> cIntegralTypes = integralTypeService.getAllTypes(partnerId);

        PartnerMember partnerMember1 = partnerMemberService.get(input.getPmId());
        params.put("partnerIds", orgIds);
        params.put("memberId", partnerMember1.getMemberId());
        List<PartnerMember> memberPartnersTo = partnerMemberReadDao.getMemberPartnersTo(params);
        List<String> pmIds = new ArrayList<>();
        for (PartnerMember partnerMember : memberPartnersTo) {
            pmIds.add(partnerMember.getId());
        }
        params.put("pmIds", pmIds);

        //推荐的人列表
        List<CUserIntegralMobileOutput> recommendPersonList = userIntegralService.getRecommendPersonList(params, page);

        //该推荐人的影响力
        Double fractionSum = userIntegralService.getRecommendItemFractionSumWithParam(params);


        Member member = memberService.get(partnerMember1.getMemberId());

        mv.addObject("list", recommendPersonList);
        mv.addObject("cIntegralTypes", cIntegralTypes);
        mv.addObject("fractionSum", fractionSum);
        mv.addObject("member", member);
        mv.addObject("pmId", input.getPmId());
        mv.addObject("mobile", mobile);
        mv.addObject("input", input);
        mv.addObject("page", page);
        return mv;
    }

    @Autowired
    private MemberGroupBizService memberGroupBizService;

    /**
     * @Description:排行榜
     * @Param: [cUserIntegral, input, page]
     * @return: org.springframework.web.servlet.ModelAndView
     * @Author: Hua Qunhao
     * @Date: 2019/9/9
     */
    @RequestMapping("leaderboardList")
    public ModelAndView leaderboardList(String typeId, Page page, CommonInput input, String memberGroupId) {
        page.setLimit(20);
        ModelAndView mv = new ModelAndView("member/leaderboardList");
        CurrentUser currentUser = RealmUtils.getNewCurrentUser();
        Map<String, Object> params = CommonInput.appendParams1(input);
        String partnerId = currentUser.getId();
        List<MemberGroup> memberGroupList = new ArrayList<>();

        if (!currentUser.isChild()) {
            memberGroupList = memberGroupService.getChildWithMyAndName(partnerId);
            List<String> orgIds = LangUtils.transform(memberGroupList, input1 -> input1.getId());
            params.put("orgIds", orgIds);
            params.put("partnerType", PartnerMember.IS_MAIN_TYPE);
        } else if (currentUser.isXzgsAdmin()) {
            memberGroupList = memberGroupService.queryAdminBranchAndXZGSList(currentUser.getId(), currentUser.getPartnerId());
            List<String> orgIds = LangUtils.transform(memberGroupList, input1 -> input1.getId());
            params.put("orgIds", orgIds);
            params.put("partnerType", PartnerMember.IS_MAIN_TYPE);
        } else {
            params.put("partnerId", partnerId);
        }
        if (StringUtils.isNotEmpty(memberGroupId)) {
            params.put("partnerId", memberGroupId);
            params.put("partnerType", null);
        }

        if (input.getcIntegralTypeId() != null) {
            params.put("typeId", input.getcIntegralTypeId());
            typeId = input.getcIntegralTypeId();
        } else {
            params.put("typeId", typeId);
            input.setcIntegralTypeId(typeId);
        }

        if (StringUtils.isNotEmpty(input.getNickName())) {
            params.put("nickName", input.getNickName());
        }

        if (StringUtils.isNotEmpty(input.getMobile())) {
            params.put("mobile", input.getMobile());
        }

        //当前机构下的积分类型
        boolean isChild = currentUser.isChild();
        if (isChild) {
            partnerId = currentUser.getPartnerId();
        }
        List<CIntegralType> cIntegralTypes = integralTypeService.getAllTypes(partnerId);
        //行动力排行榜列表
        List<CUserIntegralMobileOutput> cUserIntegralMobileOutputs;
        //总积分
        Double totalScore = 0d;

        params.put("cuiPartnerId", partnerId);
        if (input.getLeaderBoardType() != null && input.getLeaderBoardType() == 1) {
            //影响力排行榜
            cUserIntegralMobileOutputs = userIntegralService.queryIntegralInfluenceRankingListWithWeb(params, page);
            //影响力总积分
            totalScore = userIntegralService.getRecommendItemFractionSumWithParam(params);
        } else {
            //行动力排行榜列表
            cUserIntegralMobileOutputs = userIntegralService.queryUserIntegralWebList(params, page);
            //行动力总积分
            totalScore = userIntegralService.getUserItemFractionSumWithParams(params);
        }
        mv.addObject("memberGroupList", memberGroupList);
        mv.addObject("list", cUserIntegralMobileOutputs);
        mv.addObject("cIntegralTypes", cIntegralTypes);
        mv.addObject("totalScore", totalScore);
        mv.addObject("typeId", typeId);
        mv.addObject("page", page);
        mv.addObject("input", input);
        mv.addObject("isChild", currentUser.isChild());
        mv.addObject("isXzgsAdmin", currentUser.isXzgsAdmin());
        mv.addObject("memberGroupId", memberGroupId);
        return mv;
    }

    @ResponseBody
    @RequestMapping(value = "listExport")
    public AjaxResult listExport(String typeId, CommonInput input, String memberGroupId) {
        CurrentUser currentUser = RealmUtils.getNewCurrentUser();
        String partnerId = currentUser.getId();
        Map<String, Object> params = CommonInput.appendParams1(input);
        if (!currentUser.isChild()) {
            List<MemberGroup> memberGroupList = memberGroupService.getChildWithMyAndName(partnerId);
            List<String> orgIds = LangUtils.transform(memberGroupList, input1 -> input1.getId());
            params.put("orgIds", orgIds);
            params.put("partnerType", PartnerMember.IS_MAIN_TYPE);
        } else if (!currentUser.isXzgsAdmin() && currentUser.isChild()) {
            params.put("partnerId", partnerId);
        }

        if (StringUtils.isNotEmpty(memberGroupId)) {
            params.put("partnerId", memberGroupId);
        }

        if (input.getcIntegralTypeId() != null) {
            params.put("typeId", input.getcIntegralTypeId());
        } else {
            params.put("typeId", typeId);
            input.setcIntegralTypeId(typeId);
        }

        if (StringUtils.isNotEmpty(input.getNickName())) {
            params.put("nickName", input.getNickName());
        }

        if (StringUtils.isNotEmpty(input.getMobile())) {
            params.put("mobile", input.getMobile());
        }

        String headName = "";
        if (input.getLeaderBoardType() != null && input.getLeaderBoardType() == 1) {
            headName = "影响力排行榜";
        } else {
            headName = "行动力排行榜";
        }

        String fileName = headName + DateUtils.todayDate() + ".xlsx";

        //行动力排行榜列表
        List<CUserIntegralMobileOutput> cUserIntegralMobileOutputs;


        try {
            ExportExcel exportExcel = null;
            List<String> headerList = new ArrayList<>();
            headerList.add("排名");
            headerList.add("昵称");
            headerList.add("手机号");
            headerList.add("积分");
            headerList.add("所属机构");
            //影响力
            if (input.getLeaderBoardType() != null && input.getLeaderBoardType() == 1) {
                cUserIntegralMobileOutputs = userIntegralService.queryIntegralInfluenceRankingListWithWeb(params, null);
            } else {
                //行动力
                cUserIntegralMobileOutputs = userIntegralService.queryUserIntegralWebList(params, null);
            }
            exportExcel = new ExportExcel(fileName, headerList);
            exportExcel = cIntegralBizToService.setDataList(cUserIntegralMobileOutputs, exportExcel);
            String allPath = cIntegralBizToService.getExcelPath(fileName, "integral", exportExcel);
            return AjaxResult.success((Object) allPath);
        } catch (IOException e) {
            logger.error("导出会员异常", e);
        }
        return AjaxResult.error("导出异常");
    }

    @ResponseBody
    @RequestMapping("branchMemberImport")
    public AjaxResult branchMemberImport(MultipartFile uploadFile, HttpServletRequest request) {
        if (uploadFile.isEmpty()) {
            return AjaxResult.error("文件不存在！");
        }
        try {
            InputStream inputStream = uploadFile.getInputStream();
            Workbook workbook = cIntegralBizToService.getWorkbook(inputStream, uploadFile.getOriginalFilename());
            cIntegralBizToService.branchMemberImport(workbook, uploadFile.getOriginalFilename(), request.getSession().getId());
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("解析文件异常", e);
            return AjaxResult.error("解析文件异常");
        }
    }

    @ResponseBody
    @RequestMapping(value = "initPartnerIdAndMemberId")
    public void initPartnerIdAndMemberId() {
        List<String> pmIds = userIntegralService.groupByPmIdList();
        for (String pmId : pmIds) {
            PartnerMember partnerMember = partnerMemberService.get(pmId);
            if (null == partnerMember) {
                continue;
            }
            String partnerId = memberGroupService.getPartnerId(partnerMember.getPartnerId());
            userIntegralService.batchUpdatePartnerAndMember(partnerId, partnerMember.getMemberId(), pmId);
        }
    }
}
